#include "Socket.h"

#include "SocketOpt.h"
#include "XnccAddress.h"

namespace xncc {
namespace foundation {

    Socket::Socket(std::shared_ptr<XnccAddress> addr) : sockaddr_(std::move(addr))
    {
        if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::UNIX_DOMAIN) {
            sockfd_ = SocketOpt::createNonblockingOrDie(AF_UNIX, IPPROTO_IP);
        }
        else if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::IPV4_TCP) {
            sockfd_ = SocketOpt::createNonblockingOrDie(AF_INET);
        }
        else if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::IPV6_TCP) {
            sockfd_ = SocketOpt::createNonblockingOrDie(AF_INET6);
        }
        else if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::IPV4_UDP) {
            sockfd_ = SocketOpt::createNonblockingOrDie(AF_INET, IPPROTO_UDP, SOCK_DGRAM);
        }
        else if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::IPV6_UDP) {
            sockfd_ = SocketOpt::createNonblockingOrDie(AF_INET6, IPPROTO_UDP, SOCK_DGRAM);
        }
    }

    shared::XNCC_ADDR_TYPE Socket::addrType() const { return sockaddr_->Type(); }

}  // namespace foundation
}  // namespace xncc